package cn.com.chengmandian.bike.service.impl;

import cn.com.chengmandian.bike.mapper.EbPriceRuleMapper;
import cn.com.chengmandian.bike.model.EbPriceRule;
import cn.com.chengmandian.bike.model.EbPriceStep;
import cn.com.chengmandian.bike.model.vo.PriceRuleVo;
import cn.com.chengmandian.bike.service.IEbPriceRuleService;
import cn.com.chengmandian.bike.service.IEbPriceStepService;
import cn.com.chengmandian.bike.utils.CaffeineUtils;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 计费规则表 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2021-12-10
 */
@Slf4j
@Service
public class EbPriceRuleServiceImpl extends ServiceImpl<EbPriceRuleMapper, EbPriceRule> implements IEbPriceRuleService {

    @Autowired
    private IEbPriceStepService priceStepService;

    @Override
    public PriceRuleVo getFromDb(Integer areaId) {
        EbPriceRule rule = this.getOne(new LambdaQueryWrapper<EbPriceRule>()
                .eq(EbPriceRule::getAreaId, areaId)
                .last("limit 1"));
        if (rule == null) {
            rule = new EbPriceRule();
            rule.setAreaId(areaId);
            this.save(rule);

            rule = this.getOne(new LambdaQueryWrapper<EbPriceRule>()
                    .eq(EbPriceRule::getAreaId, areaId)
                    .last("limit 1"));
        }
        PriceRuleVo priceRuleVo = new PriceRuleVo();
        BeanUtils.copyProperties(rule, priceRuleVo);

        List<EbPriceStep> priceSteps = priceStepService.list(new LambdaQueryWrapper<EbPriceStep>()
                .eq(EbPriceStep::getAreaId, areaId)
                .orderByAsc(EbPriceStep::getMinute));
        priceRuleVo.setPriceSteps(priceSteps);
        return priceRuleVo;
    }

    @Override
    public PriceRuleVo getRule(Integer areaId) {
        PriceRuleVo vo = CaffeineUtils.getPriceRule(LocalMapUtil.getAgentInfo().getId() + "_" + areaId);
        if (vo != null) return vo;
        return loadCache(LocalMapUtil.getAgentInfo().getId(), areaId);
    }

    @Override
    public PriceRuleVo loadCache(Integer agentId, Integer areaId) {
        PriceRuleVo priceRuleVo = this.getFromDb(areaId);

        CaffeineUtils.putPriceRule(agentId + "_" + areaId, priceRuleVo);

        log.info("价格规则缓存已更新：{}", areaId);
        return priceRuleVo;
    }
}
